﻿/***********************************************************************
 * <copyright file="ValidateLength.cs" company="BUCA JSC">
 * -->    Copyright (C) statement. All right reserved
 * </copyright>
 * 
 * Created:   LinhMC
 * Email:    linhmc@buca.vn
 * Website:
 * Create Date: Thursday, October 17, 2013
 * Usage: 
 * 
 * RevisionHistory: 
 * Date         Author               Description 
 * 
 * ************************************************************************/

namespace BusinessObjects.BusinessRules
{
    /// <summary>
    ///     Length validation rule.
    ///     Length must be between given min and max values.
    /// </summary>
    public class ValidateLength : BusinessRule
    {
        private readonly int _max;
        private readonly int _min;

        /// <summary>
        ///     Initializes a new instance of the <see cref="ValidateLength" /> class.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="min">The minimum.</param>
        /// <param name="max">The maximum.</param>
        public ValidateLength(string propertyName, int min, int max)
            : base(propertyName)
        {
            _min = min;
            _max = max;

            ErrorMessage = string.Format("{0} must be between {1} and {2} characters long.", propertyName, _min, _max);
        }

        /// <summary>
        ///     Initializes a new instance of the <see cref="ValidateLength" /> class.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <param name="min">The minimum.</param>
        /// <param name="max">The maximum.</param>
        public ValidateLength(string propertyName, string errorMessage, int min, int max)
            : this(propertyName, min, max)
        {
            if (errorMessage != null) ErrorMessage = errorMessage;
        }

        /// <summary>
        ///     Validation method. To be implemented in derived classes.
        /// </summary>
        /// <param name="businessObject">The business object.</param>
        /// <returns>
        ///     Boolean value
        /// </returns>
        public override bool Validate(BusinessObject businessObject)
        {
            int length = GetPropertyValue(businessObject).ToString().Length;
            return length >= _min && length <= _max;
        }
    }
}